import { where } from 'sequelize/types'
import { newUserinfoType } from '../controller'
import Blog from '../db/models/Blog'
import Comments from '../db/models/Comments'
import User from '../db/models/User'

export async function getUserinfo(options: { user_id?: number; userName?: string | string[] | undefined; email?: string | string[] | undefined; password?: string }) {
  const result = await User.findOne({
    //结果只保留json格式的dataValues，不保留其他多余的参数
    attributes: ['user_id', 'userName', 'nickName', 'email', 'gender', 'avatar'],
    //如果传入了password就以{ userName, password }为where语句，否则只传入userName作为where语句
    where: options
  })
  return result
}
export async function getUserinfoById(user_id: number) {
  const result = await User.findOne({
    //结果只保留json格式的dataValues，不保留其他多余的参数
    attributes: ['nickName', 'gender', 'avatar'],
    //如果传入了password就以{ userName, password }为where语句，否则只传入userName作为where语句
    where: { user_id }
  })
  return result
}
export async function createUser(userinfo: User) {
  await User.create(userinfo)
}

export async function updateUserinfo(user_id: number, newUserinfo: newUserinfoType) {
  await User.update(newUserinfo, {
    where: {
      user_id
    }
  })
}
export async function createBlog(blog: { user_id: number; content: string; image?: string[] }) {
  return await Blog.create(blog)
}
export async function getOneBlog(blog_id: string | string[] | undefined) {
  const result = await Blog.findOne({
    attributes: ['image', 'content', 'thumb_up'],
    include: [
      {
        model: User,
        attributes: ['nickName', 'avatar', 'user_id']
      },
      {
        model: Comments,
        attributes: ['content'],
        include: [{ model: User, attributes: ['nickName', 'avatar', 'user_id'] }],
        //最多传5条记录，其他的点更多查看具体信息
        limit: 5
      }
    ],
    where: { blog_id }
  })

  return result
}
export async function getBlogList(option: { user_id?: number; page?: number; limit?: number }) {
  const { page, limit, user_id } = option
  const result = await Blog.findAndCountAll({
    attributes: ['image', 'content', 'thumb_up', 'blog_id', 'createdAt'],
    include: [
      {
        model: User,
        attributes: ['nickName', 'avatar', 'user_id']
      }
    ],
    offset: page! * limit! - limit! || undefined,
    limit: limit || undefined,
    where: (user_id && { user_id }) || undefined
  })

  return result
}

export async function createComment(comment: { blog_id: number; user_id: number; content: string }) {
  return await Comments.create(comment)
}
export async function getComments(blog_id: number, page?: number, limit?: number) {
  return await Comments.findAndCountAll({
    attributes: ['comment_id', 'content', 'thumb_up', 'createdAt'],
    // 分页公式：offset:=page * limit - limit
    offset: page! * limit! - limit! || undefined,
    limit: limit || undefined,
    include: [{ model: User, attributes: ['user_id', 'avatar', 'nickName'] }],
    where: { blog_id }
  })
}
